import "./Feeding.css"


import React, { useState, useEffect } from 'react';
import axios from 'axios';
import DataTable from 'react-data-table-component';
import { Dialog, DialogTitle, DialogContent, Button } from '@mui/material';
import AddFeedingDialog from './AddFeedingDialog';
import {paginationComponentOptions, customTableStyles} from '../Constants'
import { useNavigate } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';


const FeedingsPage = () => {
    const [feedings, setFeedings] = useState([]);
    const [openDialog, setOpenDialog] = useState(false);
    const navigate = useNavigate();

  const goBack = () => {
    navigate('/home')
  };

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/feeding`, {headers});
            const formattedData = response.data.feedings.map(feeding => ({
                id: feeding.id,
                amount: feeding.amount,
                feedingTime: new Date(feeding.feeding_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                foodBrand: feeding.food_brand,
                foodBatch: feeding.food_batch,
                foodSize: feeding.food_size,
                populationFed: feeding.pname,
                key: feeding.id,
            }));
            setFeedings(formattedData);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    const handleOpenDialog = () => {
        setOpenDialog(true);
    };

    const handleCloseDialog = () => {
        setOpenDialog(false);
    };

    const columns = [
        { name: 'Популяция', selector: row => row.populationFed, sortable: true },
        { name: 'Время кормления', selector: row => row.feedingTime, sortable: true },
        { name: 'Количество', selector: row => row.amount },
        { name: 'Марка', selector: row => row.foodBrand, sortable: true },
        { name: 'Партия', selector: row => row.foodBatch, sortable: true },
        { name: 'Размер', selector: row => row.foodSize, wrap: true },
    ];

    return (
        <div style={{ padding: 30 }}>
             <button onClick={goBack}>
        <FontAwesomeIcon icon={faArrowLeft} /> Главное меню
      </button>
            <div className="header">
                <div className="left">
                    <h1 style={{ paddingLeft: '20px', fontWeight: 'normal' }}>Кормление</h1>
                </div>
                <div className="right">
                    <button onClick={handleOpenDialog}>Добавить новые данные</button>
                </div>
            </div>
            <DataTable
                columns={columns}
                data={feedings}
                pagination
                defaultSortFieldId={1}
                paginationComponentOptions={paginationComponentOptions}
                customStyles={customTableStyles}
            />
            <AddFeedingDialog open={openDialog} onClose={handleCloseDialog} fetchData={fetchData} />
        </div>
    );
};

export default FeedingsPage;


